package com.tandan.mqttdemo0730.scheduler;

import com.tandan.mqttdemo0730.service.MqttService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * MQTT数据定时推送任务
 */
@Component
public class MqttDataScheduler {

    private static final Logger logger = LoggerFactory.getLogger(MqttDataScheduler.class);

    @Autowired
    private MqttService mqttService;

    @Value("${mqtt.topic}")
    private String defaultTopic;

    private final AtomicLong messageCounter = new AtomicLong(0);
    private final Random random = new Random();

    /**
     * 使用配置文件中的固定频率推送数据
     * 从application.properties中的scheduling.fixed-rate读取间隔时间
     */
    @Scheduled(fixedRateString = "${scheduling.fixed-rate}")
    public void publishSensorData() {
        try {
            if (!mqttService.isConnected()) {
                logger.warn("MQTT未连接，跳过本次数据推送");
                return;
            }

            // 生成传感器数据
            Map<String, Object> sensorData = generateSensorData();
            
            // 发布到默认主题
            mqttService.publishObject(sensorData);
            
            long count = messageCounter.incrementAndGet();
            logger.info("定时推送传感器数据完成 - 消息序号: {}", count);

        } catch (Exception e) {
            logger.error("定时推送数据时发生错误", e);
        }
    }

    /**
     * 每分钟推送一次系统状态数据
     */
    @Scheduled(fixedRate = 60000) // 60秒
    public void publishSystemStatus() {
        try {
            if (!mqttService.isConnected()) {
                return;
            }

            Map<String, Object> systemStatus = generateSystemStatus();
            
            // 发布到系统状态主题
            mqttService.publishObject("system/status", systemStatus);
            
            logger.info("推送系统状态数据完成");

        } catch (Exception e) {
            logger.error("推送系统状态数据时发生错误", e);
        }
    }

    /**
     * 每30秒推送一次设备心跳
     */
    @Scheduled(fixedRate = 30000) // 30秒
    public void publishHeartbeat() {
        try {
            if (!mqttService.isConnected()) {
                return;
            }

            Map<String, Object> heartbeat = new HashMap<>();
            heartbeat.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            heartbeat.put("deviceId", "mqtt-demo-device");
            heartbeat.put("status", "online");
            heartbeat.put("uptime", System.currentTimeMillis());
            heartbeat.put("messageCount", messageCounter.get());

            // 发布到心跳主题
            mqttService.publishObject("device/heartbeat", heartbeat);
            
            logger.debug("推送设备心跳完成");

        } catch (Exception e) {
            logger.error("推送设备心跳时发生错误", e);
        }
    }



    /**
     * 生成模拟传感器数据
     */
    private Map<String, Object> generateSensorData() {rem
        Map<String, Object> data = new HashMap<>();
        
        data.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        data.put("messageId", messageCounter.get() + 1);
        data.put("deviceId", "sensor" + MqttService.getNumber()  );
        data.put("deviceType", "environmental_sensor");
        data.put("location", "机房A区");
        
        // 环境数据
        Map<String, Object> environmental = new HashMap<>();
        environmental.put("temperature", Math.round((20 + random.nextDouble() * 15) * 100.0) / 100.0); // 20-35度，保留2位小数
        environmental.put("humidity", Math.round((40 + random.nextDouble() * 40) * 100.0) / 100.0);    // 40-80%
        environmental.put("pressure", Math.round((1000 + random.nextDouble() * 50) * 100.0) / 100.0);  // 1000-1050 hPa
        environmental.put("co2", 400 + random.nextInt(600)); // 400-1000 ppm
        environmental.put("light", random.nextInt(1000)); // 0-1000 lux
        
        data.put("environmental", environmental);
        
        // 设备状态
        Map<String, Object> deviceStatus = new HashMap<>();
        deviceStatus.put("battery", 85 + random.nextInt(15)); // 85-100%
        deviceStatus.put("signal", -30 - random.nextInt(50)); // -30 到 -80 dBm
        deviceStatus.put("errorCount", random.nextInt(3));
        
        data.put("deviceStatus", deviceStatus);
        
        return data;
    }

    /**
     * 生成系统状态数据
     */
    private Map<String, Object> generateSystemStatus() {
        Map<String, Object> status = new HashMap<>();
        
        status.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        status.put("applicationName", "mqtt-demo0730");
        status.put("version", "1.0.0");
        status.put("status", "running");
        
        // JVM信息
        Runtime runtime = Runtime.getRuntime();
        Map<String, Object> jvm = new HashMap<>();
        jvm.put("totalMemory", runtime.totalMemory());
        jvm.put("freeMemory", runtime.freeMemory());
        jvm.put("usedMemory", runtime.totalMemory() - runtime.freeMemory());
        jvm.put("maxMemory", runtime.maxMemory());
        jvm.put("processors", runtime.availableProcessors());
        
        status.put("jvm", jvm);
        
        // MQTT连接状态
        Map<String, Object> mqtt = new HashMap<>();
        mqtt.put("connected", mqttService.isConnected());
        mqtt.put("messagesSent", messageCounter.get());
        
        status.put("mqtt", mqtt);
        
        return status;
    }

    /**
     * 获取已发送消息计数
     */
    public long getMessageCount() {
        return messageCounter.get();
    }
}